import React, { useState, useRef } from 'react';
import { Upload, Button, Card, Row, Col, Tabs, Radio, Input, Slider, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import { fabric } from 'fabric';
import styles from '../../../styles/ToolDetail.module.css';

const { TabPane } = Tabs;

// 自定义颜色选择器
const ColorPicker = ({ value, onChange }) => {
  return (
    <div style={{ display: 'flex', alignItems: 'center' }}>
      <input
        type="color"
        value={value}
        onChange={(e) => onChange(e.target.value)}
        style={{ 
          width: '36px', 
          height: '36px', 
          padding: '0', 
          margin: '0 8px 0 0',
          border: '1px solid #d9d9d9',
          borderRadius: '4px',
          cursor: 'pointer'
        }}
      />
      <Input 
        value={value} 
        onChange={(e) => onChange(e.target.value)}
        style={{ width: '100px' }}
      />
    </div>
  );
};

/**
 * 水印处理组件
 * 支持添加文字水印、图片水印和简单的水印移除功能
 */
const WatermarkTool = ({ originalImage, onProcessed }) => {
  const [loading, setLoading] = useState(false);
  const [mode, setMode] = useState('add'); // 'add' 或 'remove'
  const [fileInfo, setFileInfo] = useState(null);
  
  // 水印添加相关状态
  const [watermarkText, setWatermarkText] = useState('水印文字');
  const [watermarkImage, setWatermarkImage] = useState(null);
  const [watermarkType, setWatermarkType] = useState('text'); // 'text' 或 'image'
  const [watermarkOpacity, setWatermarkOpacity] = useState(30);
  const [watermarkColor, setWatermarkColor] = useState('#000000');
  const [watermarkSize, setWatermarkSize] = useState(24);
  const [watermarkPosition, setWatermarkPosition] = useState('center');
  const [watermarkAngle, setWatermarkAngle] = useState(0); // 水印旋转角度
  
  const canvasRef = useRef(null);
  const fabricCanvasRef = useRef(null);

  // 上传水印图片
  const beforeUploadWatermark = (file) => {
    const isImage = file.type.startsWith('image/');
    if (!isImage) {
      message.error('只能上传图片文件!');
      return false;
    }
    
    const isLt1M = file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
      message.error('水印图片必须小于1MB!');
      return false;
    }
    
    // 显示水印图片预览
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => {
      setWatermarkImage(reader.result);
    };
    
    return false; // 阻止自动上传
  };
  
  // 修改初始化Canvas方法，确保加载图片完成后再进行后续操作
  const initCanvas = (imgElement) => {
    if (fabricCanvasRef.current) {
      fabricCanvasRef.current.dispose();
    }
    
    const canvas = new fabric.Canvas(canvasRef.current, {
      width: imgElement.width,
      height: imgElement.height
    });
    
    fabricCanvasRef.current = canvas;
    
    // 添加原始图片到画布并确保异步加载完成
    return new Promise((resolve) => {
      fabric.Image.fromURL(originalImage, (img) => {
        canvas.setBackgroundImage(img, canvas.renderAll.bind(canvas), {
          scaleX: canvas.width / img.width,
          scaleY: canvas.height / img.height
        });
        resolve(canvas);
      });
    });
  };
  
  // 修改处理水印添加方法，使用异步/等待来确保操作顺序正确
  const handleAddWatermark = async () => {
    if (!originalImage) {
      message.error('请先上传图片');
      return;
    }
    
    setLoading(true);
    
    try {
      const img = new Image();
      
      // 使用Promise来等待图片加载完成
      await new Promise((resolve, reject) => {
        img.onload = resolve;
        img.onerror = reject;
        img.src = originalImage;
      });
      
      // 初始化Canvas并等待完成
      const canvas = await initCanvas(img);
      
      if (watermarkType === 'text') {
        // 添加文字水印
        const text = new fabric.Text(watermarkText, {
          fontSize: watermarkSize,
          fill: watermarkColor,
          opacity: watermarkOpacity / 100,
          angle: watermarkAngle
        });
        
        // 根据选择的位置确定坐标
        switch (watermarkPosition) {
          case 'topLeft':
            text.set({ left: 20, top: 20 });
            break;
          case 'topRight':
            text.set({ left: canvas.width - text.width - 20, top: 20 });
            break;
          case 'bottomLeft':
            text.set({ left: 20, top: canvas.height - text.height - 20 });
            break;
          case 'bottomRight':
            text.set({ left: canvas.width - text.width - 20, top: canvas.height - text.height - 20 });
            break;
          case 'center':
          default:
            text.set({ left: canvas.width / 2, top: canvas.height / 2, originX: 'center', originY: 'center' });
            break;
        }
        
        // 添加文字并确保渲染
        canvas.add(text);
        canvas.renderAll();
        
        // 输出处理后的图片
        const processedImage = canvas.toDataURL({
          format: 'png',
          quality: 0.95
        });
        onProcessed(processedImage);
        setLoading(false);
      } else if (watermarkType === 'image' && watermarkImage) {
        // 添加图片水印
        fabric.Image.fromURL(watermarkImage, (watermark) => {
          // 缩放水印图片
          const maxSize = 150;
          const scale = Math.min(maxSize / watermark.width, maxSize / watermark.height);
          watermark.scale(scale);
          
          watermark.set({
            opacity: watermarkOpacity / 100,
            angle: watermarkAngle
          });
          
          // 根据选择的位置确定坐标
          switch (watermarkPosition) {
            case 'topLeft':
              watermark.set({ left: 20, top: 20 });
              break;
            case 'topRight':
              watermark.set({ left: canvas.width - watermark.getScaledWidth() - 20, top: 20 });
              break;
            case 'bottomLeft':
              watermark.set({ left: 20, top: canvas.height - watermark.getScaledHeight() - 20 });
              break;
            case 'bottomRight':
              watermark.set({ left: canvas.width - watermark.getScaledWidth() - 20, top: canvas.height - watermark.getScaledHeight() - 20 });
              break;
            case 'center':
            default:
              watermark.set({ left: canvas.width / 2, top: canvas.height / 2, originX: 'center', originY: 'center' });
              break;
          }
          
          canvas.add(watermark);
          canvas.renderAll();
          
          // 输出处理后的图片
          const processedImage = canvas.toDataURL({
            format: 'png',
            quality: 0.95
          });
          onProcessed(processedImage);
          setLoading(false);
        });
      } else {
        message.error('水印图片未上传');
        setLoading(false);
      }
    } catch (error) {
      console.error('处理水印时出错:', error);
      message.error('处理水印时出错');
      setLoading(false);
    }
  };
  
  // 处理水印移除
  const handleRemoveWatermark = () => {
    if (!originalImage) {
      message.error('请先上传图片');
      return;
    }
    
    setLoading(true);
    
    // 这里我们使用简化的水印移除算法
    // 实际应用中可能需要更复杂的算法或AI技术
    
    const img = new Image();
    img.onload = () => {
      const canvas = document.createElement('canvas');
      canvas.width = img.width;
      canvas.height = img.height;
      const ctx = canvas.getContext('2d');
      
      // 绘制原始图片
      ctx.drawImage(img, 0, 0);
      
      // 应用简单的高斯模糊和锐化算法模拟水印移除
      // 这只是一个简化的示例，实际应用中可能需要更复杂的算法
      const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
      const data = imageData.data;
      
      // 模拟水印移除效果（简化版本，实际项目可能需要更复杂的算法）
      for (let i = 0; i < data.length; i += 4) {
        // 轻微调整亮度和对比度
        const brightness = 10;
        const contrast = 1.2;
        
        data[i] = Math.min(255, Math.max(0, (data[i] - 128) * contrast + 128 + brightness));
        data[i + 1] = Math.min(255, Math.max(0, (data[i + 1] - 128) * contrast + 128 + brightness));
        data[i + 2] = Math.min(255, Math.max(0, (data[i + 2] - 128) * contrast + 128 + brightness));
      }
      
      ctx.putImageData(imageData, 0, 0);
      
      // 输出处理后的图片
      setTimeout(() => {
        const processedImage = canvas.toDataURL('image/png', 0.95);
        onProcessed(processedImage);
        setLoading(false);
        message.info('水印移除功能是简化版本，效果可能不尽如人意。实际应用需要更复杂的算法。');
      }, 1000);
    };
    
    img.src = originalImage;
  };
  
  const positionOptions = [
    { label: '左上角', value: 'topLeft' },
    { label: '右上角', value: 'topRight' },
    { label: '左下角', value: 'bottomLeft' },
    { label: '右下角', value: 'bottomRight' },
    { label: '中心', value: 'center' },
  ];
  
  return (
    <div className={styles.watermarkToolContainer}>
      <Tabs 
        activeKey={mode} 
        onChange={(key) => setMode(key)}
      >
        <TabPane tab="添加水印" key="add">
          <div className={styles.watermarkSettings}>
            <Row gutter={24}>
              <Col xs={24} md={12}>
                <div className={styles.imagePreview}>
                  <img src={originalImage} alt="预览" style={{ maxWidth: '100%' }} />
                </div>
              </Col>
              
              <Col xs={24} md={12}>
                <h3>水印设置</h3>
                
                <div className={styles.settingItem}>
                  <p>水印类型:</p>
                  <Radio.Group 
                    value={watermarkType} 
                    onChange={(e) => setWatermarkType(e.target.value)}
                  >
                    <Radio value="text">文字水印</Radio>
                    <Radio value="image">图片水印</Radio>
                  </Radio.Group>
                </div>
                
                {watermarkType === 'text' ? (
                  <>
                    <div className={styles.settingItem}>
                      <p>水印文字:</p>
                      <Input 
                        value={watermarkText} 
                        onChange={(e) => setWatermarkText(e.target.value)} 
                        placeholder="请输入水印文字"
                      />
                    </div>
                    
                    <div className={styles.settingItem}>
                      <p>文字大小: {watermarkSize}px</p>
                      <Slider 
                        min={12} 
                        max={72} 
                        value={watermarkSize} 
                        onChange={setWatermarkSize} 
                      />
                    </div>
                    
                    <div className={styles.settingItem}>
                      <p>文字颜色:</p>
                      <ColorPicker 
                        value={watermarkColor} 
                        onChange={setWatermarkColor} 
                      />
                    </div>
                  </>
                ) : (
                  <div className={styles.settingItem}>
                    <p>水印图片:</p>
                    <Upload
                      name="watermarkImage"
                      listType="picture-card"
                      className="watermark-image-uploader"
                      showUploadList={false}
                      beforeUpload={beforeUploadWatermark}
                    >
                      {watermarkImage ? (
                        <img 
                          src={watermarkImage} 
                          alt="水印图片" 
                          style={{ width: '100%' }} 
                        />
                      ) : (
                        <div>
                          <UploadOutlined />
                          <div style={{ marginTop: 8 }}>上传水印图片</div>
                        </div>
                      )}
                    </Upload>
                    <p className="upload-hint">建议使用透明背景的PNG图片，大小不超过1MB</p>
                  </div>
                )}
                
                <div className={styles.settingItem}>
                  <p>水印位置:</p>
                  <Radio.Group 
                    value={watermarkPosition} 
                    onChange={(e) => setWatermarkPosition(e.target.value)}
                    optionType="button"
                    buttonStyle="solid"
                  >
                    {positionOptions.map(option => (
                      <Radio.Button key={option.value} value={option.value}>
                        {option.label}
                      </Radio.Button>
                    ))}
                  </Radio.Group>
                </div>
                
                <div className={styles.settingItem}>
                  <p>不透明度: {watermarkOpacity}%</p>
                  <Slider 
                    min={10} 
                    max={100} 
                    value={watermarkOpacity} 
                    onChange={setWatermarkOpacity} 
                  />
                </div>
                
                <div className={styles.settingItem}>
                  <p>旋转角度: {watermarkAngle}°</p>
                  <Slider 
                    min={-45} 
                    max={45} 
                    value={watermarkAngle} 
                    onChange={setWatermarkAngle} 
                  />
                </div>
                
                <Button
                  type="primary"
                  size="large"
                  onClick={handleAddWatermark}
                  loading={loading}
                  style={{ marginTop: '16px' }}
                  block
                >
                  添加水印
                </Button>
              </Col>
            </Row>
            
            {/* 隐藏的canvas用于Fabric.js渲染 */}
            <canvas ref={canvasRef} style={{ display: 'none' }} />
          </div>
        </TabPane>
        
        <TabPane tab="移除水印" key="remove">
          <div className={styles.watermarkSettings}>
            <Row gutter={24}>
              <Col xs={24} md={12}>
                <div className={styles.imagePreview}>
                  <img src={originalImage} alt="预览" style={{ maxWidth: '100%' }} />
                </div>
              </Col>
              
              <Col xs={24} md={12}>
                <h3>水印移除设置</h3>
                <p className={styles.removalNote}>
                  水印移除功能会尝试自动检测并移除图片中的水印。
                  效果取决于原始水印的类型和图片质量。
                </p>
                
                <Button
                  type="primary"
                  size="large"
                  onClick={handleRemoveWatermark}
                  loading={loading}
                  style={{ marginTop: '16px' }}
                  block
                >
                  尝试移除水印
                </Button>
              </Col>
            </Row>
          </div>
        </TabPane>
      </Tabs>
    </div>
  );
};

export default WatermarkTool; 